package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.entity.GoodsType;
import com.atguigu.jxc.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;


    @Override
    public ServiceVO getCode() {

        // 获取当前商品最大编码
        String code = goodsDao.getMaxCode();

        // 在现有编码上加1
        Integer intCode = Integer.parseInt(code) + 1;

        // 将编码重新格式化为4位数字符串形式
        String unitCode = intCode.toString();

        for (int i = 4; i > intCode.toString().length(); i--) {

            unitCode = "0" + unitCode;

        }
        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, unitCode);
    }


    @Override
    public List<Map<String, Object>> loadGoodsType() {
        return trace(-1);
    }

    private List<Map<String, Object>> trace(Integer pid) {
        List<GoodsType> goodsTypeList = goodsDao.traceCategory(pid);
        if (CollectionUtils.isEmpty(goodsTypeList)) {
            return null;
        }
        return goodsTypeList.stream().map(goodsType -> {
            Map<String, Object> map = new HashMap<>();
            map.put("text", goodsType.getGoodsTypeName());
            map.put("id", goodsType.getGoodsTypeId());
            // 递归查询
            List<Map<String, Object>> item = trace(goodsType.getGoodsTypeId());
            if (!CollectionUtils.isEmpty(item)) {
                map.put("children", item);
            } else {
                map.put("children", null);
            }
            return map;
        }).collect(Collectors.toList());

    }

    @Override
    public Map<String, Object> listInventory(String codeOrName,
                                             Integer goodsTypeId,
                                             Integer page,
                                             Integer rows) {
        page = page == 0 ? 1 : page;
        int offSet = (page - 1) * rows;
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", goodsDao.getGoodsCount(codeOrName, goodsTypeId));
        map.put("rows", goodsDao.getGoodsList(codeOrName, goodsTypeId, offSet, rows));
        return map;
    }
}
